<?php

namespace app\common\traits;

use think\exception\HttpResponseException;
use think\Paginator;
use think\Response;
use think\response\Json;

/**
 * API输出基类
 * Trait JumpTrait
 * @package app\common\traits
 */
trait JumpTrait
{
    /**
     * 接口操作成功，返回信息
     * @param string $msg
     * @param array $data
     * @param int $code
     * @param int $show
     * @return Json
     */
    protected function success(string $msg = 'success', array $data = [], int $code = 200, int $show = 1): Json
    {
        return $this->result($code, $show, $msg, $data);
    }



    /**
     * 接口操作失败，返回信息
     * @param string $msg
     * @param array $data
     * @param int $code
     * @param int $show
     * @return Json
     */
    protected function fail(string $msg = 'fail', array $data = [], int $code = 400, int $show = 1): Json
    {
        return $this->result($code, $show, $msg, $data);
    }



    /**
     * 接口返回数据
     * @param $data
     * @return Json
     */
    protected function data($data): Json
    {
        return $this->success('', $data, 200, 0);
    }



    /**
     * 接口返回信息
     * @param int $code
     * @param int $show
     * @param string $msg
     * @param array $data
     * @param int $httpStatus
     * @return Json
     */
    protected function result(int $code, int $show, string $msg = 'OK', array $data = [], int $httpStatus = 200): Json
    {
        $result = compact('code', 'show', 'msg', 'data');
        return json($result, $httpStatus);
    }



    /**
     * 抛出异常json
     * @param string $msg
     * @param array $data
     * @param int $code
     * @param int $show
     * @return Json
     */
    protected function throw(string $msg = 'fail', array $data = [], int $code = 500, int $show = 1): Json
    {
        $data = compact('code', 'show', 'msg', 'data');
        $response = Response::create($data, 'json', 200);
        throw new HttpResponseException($response);
    }


    /**
     * 数据列表
     * @param Paginator $lists
     * @return Json
     */
    protected function dataLists(Paginator $lists): Json
    {
        $data = [
            'lists' => $lists->items(),
            'count' => $lists->count(),
            'page' => $lists->currentPage(),
            'page_size' => $lists->listRows(),
        ];
        return $this->success('', $data, 200, 0);
    }
}